package thread.threadlocal;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: ch-general
 * @description: 用于线程池复用线程共享变量
 * @author: cuihao
 * @create: 2019-05-28 13:22
 **/
public class MyTransmittableThreadLocal {

    private static final TransmittableThreadLocal<Object> inheritableThreadLocal = new TransmittableThreadLocal<Object>();

    public static void main(String[] args) {

        // 使用工具累封装线程池,XXXWrapper继承于线程池
        ExecutorService poll = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(3));

        System.out.println(Thread.currentThread() + " 主线程开始... ");

        inheritableThreadLocal.set(Thread.currentThread() + " Hello World ");
        // 重写execute方法，主线程最新的值
        poll.execute(new MyIntegerTask());

        try {
            Thread.sleep(300);
        } catch (Exception e) {
        }

        inheritableThreadLocal.set(Thread.currentThread() + " 你好 ");
        poll.execute(new MyIntegerTask());
    }

    public static class MyIntegerTask implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread() + " 子线程开始... ");
            System.out.println(Thread.currentThread() + " 子线程获取变量: " + inheritableThreadLocal.get());
        }
    }
}